package com.eling.elcms.travel.service.impl;

import com.eling.elcms.core.AppContext;
import com.eling.elcms.core.exception.BusinessException;
import com.eling.elcms.core.service.impl.GenericManagerImpl;
import com.eling.elcms.core.util.PropertyUtils;
import com.eling.elcms.travel.dao.IPlanDao;
import com.eling.elcms.travel.model.Plan;
import com.eling.elcms.travel.model.PlanItem;
import com.eling.elcms.travel.model.view.PlanItemView;
import com.eling.elcms.travel.model.view.PlanView;
import com.eling.elcms.travel.service.IPlanItemManager;
import com.eling.elcms.travel.service.IPlanManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PlanManagerImpl extends GenericManagerImpl<Plan, Long> implements IPlanManager{
	
	IPlanDao planDao;
	
	@Autowired
	private IPlanItemManager itemManager;
	
	@Autowired
	public void setMakePlanDao(IPlanDao planDao) {
		this.dao = planDao;
		this.planDao = planDao;
	}
	
	@Override
	public Plan saveplan(PlanView view) {
		view.getPlan().setEditor(AppContext.curUser().getName());
		List<PlanItem> list = view.getList();
		if(null != view.getPlan().getPkPlan()){
			remove(view.getPlan().getPkPlan());
			view.getPlan().setPkPlan(null);
			view.getPlan().setVersion(0);
			for(PlanItem item : list){
				item.setPkPlanItem(null);
				item.setVersion(0);
			}
		}
		
		/** 对录入数据完整性校验*/
		
		
		/** 年度+版本号 唯一性验证*/
		Plan cond = new Plan();
		cond.setYear(view.getPlan().getYear());
		cond.setVerNumber(view.getPlan().getVerNumber());
		PropertyUtils.setProperty(cond, "yearEnd", cond.getYear());
		List<Plan> lists = query(cond);
		if(!lists.isEmpty()){
			if(!lists.get(0).getPkPlan().equals(view.getPlan().getPkPlan())){
				throw new BusinessException("本年度内版本号重复，请重新输入版本号！");
			}
		}
		/** 数据无误进行存储*/
		view.getPlan().setPlanItem(new HashSet<PlanItem>(itemManager.save(list)));
		return save(view.getPlan());
	}
	
	public List<Plan> queryStatus() {
		Plan plan = new Plan();
		List<Plan> planCond = query(plan);
		List<Plan> plans = new ArrayList<Plan>();
		for(int i = 0;i < planCond.size();i++){
			if(!planCond.get(i).getStatus().getDisplay().equals("暂存")){
				plans.add(planCond.get(i));
			}
		}
		return plans;
	}

	@Override
	public List<PlanItem> inquirySignup(PlanView view) {
		return itemManager.inquirySignup(view.getList());
	}

	@Override
	public PlanItemView selectplan(Plan plan) {
		return planDao.seletplan(plan);
	}

	@Override
	public List<Plan> queryYear(Plan plan) {
		List<Plan> list = getAll();
		List<Plan> listReturn = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		Map<String , Plan> map = new HashMap<>();
		for(Plan p : list){
			map.put(sdf.format(p.getYear()),plan);
		}
		Set<String> set = map.keySet();
		for(String key : set){
			listReturn.add(map.get(key));
		}
		return listReturn;
	}
}
